<?php

namespace App\Traits;

use App\Http\Requests\IntValRequest;

trait BaseApiFunc {

	public function index(IntValRequest $request) {
		$this->model = $this->model->withOutStatus();
		$page = (int) $request->query('page', 1);
		$query = $request->query('query', '');
		$page_size = $this->page_size;
		$total_nums = $this->model->countRaws($query);

		$list = $this->getResourceCollection($this->model->page($page, $page_size))->additional(['meta' => compact(
			'total_nums', 'page_size', 'page')]);
		return $this->response->withTitle()->withCollectionSuccess($list);
	}

	public function edit($id) {
		$this->model = $this->model->withOutStatus();
		$list = $this->getResource($this->model->getById($id))->type('edit');
		return $this->response->withSuccess($list);
	}

	public function update(IntValRequest $request, $id) {
		$this->model = $this->model->withOutStatus();
		$this->model->update($id, $request->all());
		return $this->response->withNoContent();
	}

	public function destroy($id) {
		if (!is_numeric($id)) {
			if (!strpos($id, ',')) {
				abort(422, 'id must be numeric');
			}
			$id = array_merge(array_filter(explode(',', $id), function ($value) {
				return is_numeric($value);
			}));
		}
		if (empty($id)) {
			abort(422, 'id must be numeric');
		}
		$this->model = $this->model->withOutStatus();
		$this->model->destroy($id);
		return $this->response->withNoContent();
	}
}